package com.wang.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wang.auto.InitDataTask;
import com.wang.auto.addSet.AddSetAutoSend;
import com.wang.auto.addSet.AddSetControlUtil;
import com.wang.conf.AppConf;
import com.wang.conf.AppData;
import com.wang.conf.DevManager;
import com.wang.packpojo.*;
import com.wang.pojo.*;
import com.wang.service.*;
import com.wang.socket.OutBoundHandler;
import com.wang.socket.SocketMap;
import com.wang.util.*;
import com.wang.webSocket.WebSocketMap;
import com.wang.webSocket.WebSocketUtil;
import io.netty.channel.ChannelHandlerContext;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


//与其他服务的连接入口
@RestController
public class ConController extends BaseController {


    //获取微信小程序token 目前主要用户mqtt服务器获取token
    @RequestMapping(value = "/getMyAppToken")
    @CrossOrigin
    public String getMyAppToken(){

        return WxMsgUtil.getMyAppToken();
    }



    //获取列表 测试使用
    @RequestMapping(value = "/getDevByType")
    @CrossOrigin
    public ResultStatus getDevByType(String type) {

        ResultStatus msg = new ResultStatus();

        List<SocketMsg> list = new ArrayList<>();
        //从全局变量中获取数据
        switch (type) {

            case "1":
                for (Map.Entry<String, Device> entry : SocketMap.deviceMap.entrySet()) {
                    SocketMsg socketMsg = null;
                    if (entry.getValue().getIsBind() == 1) {
                        socketMsg = new SocketMsg("", entry.getKey(), "已绑定");
                    } else {
                        socketMsg = new SocketMsg("", entry.getKey(), "未绑定");
                    }


                    list.add(socketMsg);
                }

                msg = new ResultStatus("success", "获取成功", list);
                break;
            case "2":
                for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
                    SocketMsg socketMsg = null;
                    if (entry.getValue().getDevice().getIsBind() == 1) {
                        socketMsg = new SocketMsg(entry.getKey(), entry.getValue().getDevice().getDevGId(), "已绑定");
                    } else {
                        socketMsg = new SocketMsg(entry.getKey(), entry.getValue().getDevice().getDevGId(), "未绑定");
                    }

                    list.add(socketMsg);
                }
                for (Map.Entry<String, ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()) {
                    SocketMsg socketMsg = null;
                    if (entry.getValue().getDevice().getIsBind() == 1) {
                        socketMsg = new SocketMsg(entry.getKey(), entry.getValue().getDevice().getDevGId(), "已绑定");
                    } else {
                        socketMsg = new SocketMsg(entry.getKey(), entry.getValue().getDevice().getDevGId(), "未绑定");
                    }

                    list.add(socketMsg);
                }
                msg = new ResultStatus("success", "获取成功", list);
                break;

            case "4":
                for (Map.Entry<String, ConMsg> entry : SocketMap.notRegDeviceMap.entrySet()) {
                    SocketMsg socketMsg = new SocketMsg(entry.getKey(), "");
                    list.add(socketMsg);
                }
                msg = new ResultStatus("success", "获取成功", list);
                break;
            case "5":
                for (Map.Entry<String, DebugConMsg> entry : WebSocketMap.clientDDCtxMap.entrySet()) {
                    SocketMsg socketMsg = new SocketMsg(getRemoteAddress(entry.getValue().getWebSocketConMsg().getCtx()), entry.getKey());
                    list.add(socketMsg);
                }
                msg = new ResultStatus("success", "获取成功", list);
                break;
            case "6":
                for (Map.Entry<String, DebugConMsg> entry : WebSocketMap.clientWEBCtxMap.entrySet()) {
                    SocketMsg socketMsg = new SocketMsg(getRemoteAddress(entry.getValue().getWebSocketConMsg().getCtx()), entry.getKey());
                    list.add(socketMsg);
                }
                msg = new ResultStatus("success", "获取成功", list);
                break;
            default:
                break;

        }
        return msg;

    }

    //更新设备列表 测试使用
    @RequestMapping(value = "/updateGlobaData")
    @CrossOrigin
    public ResultStatus updateGlobaData() {
        InitDataTask.getDevList();

        ResultStatus msg = new ResultStatus("success", "更新成功");
        return msg;
    }

    //更新单个设备配置
    @RequestMapping(value = "/updateDevConf")
    @CrossOrigin
    public ResultStatus updateDevConf(String devGId) {

        DevManager.updateDevDate(devGId);
        ResultStatus msg = new ResultStatus("success", "更新成功");
        return msg;

    }

    //查询单个设备的配置
    @RequestMapping(value = "selectDevConf")
    @CrossOrigin
    public ResultStatus selectDevConf(String devGId){


        ConMsg conMsg = null;
        Integer flag = 0;
        for(Map.Entry<String,ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()){
            if(entry.getValue().getDevice().getDevGId().equals(devGId)){
               conMsg = entry.getValue();
                flag = 1;
                break;
            }
        }
        if(flag == 0) {
            for (Map.Entry<String, ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()) {
                if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                    conMsg = entry.getValue();
                    break;
                }
            }
        }

        return new ResultStatus("success","获取成功",conMsg);
    }



    //服务间通讯  //添加设备  传递的设备参数devGId 暂时不使用
    @RequestMapping(value = "/addProdDev")
    @CrossOrigin
    public String addProdDev(String devGId) {

        System.out.println("收到添加的设备:" + devGId);

        //暂时通知方法更新全局变量数据  后期只增加一个变量  然后剔除这个设备的连接  让设备重连
        InitDataTask.getDevList();

        //Device prodDevice = deviceService.selectDeviceByDevGId(devGId);
       /* if(prodDevice!=null){
          //更新全局变量中的状态
            if(SocketMap.deviceMap.containsKey(devGId)){
                 SocketMap.deviceMap.get(devGId).setIsBind(1);
            }
            for(Map.Entry<String,ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()){
                if(entry.getValue().getDevice().getDevGId().equals(devGId)){
                    entry.getValue().getDevice().setIsBind(1);

                    break;
                }
            }
            for(Map.Entry<String,ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()){
                if(entry.getValue().getDevice().getDevGId().equals(devGId)){
                    entry.getValue().getDevice().setIsBind(1);
                    break;
                }
            }

        }
*/
        String msg = "success";
        //并且添加已注册设备列表

        return msg;

    }

    //服务间通讯  //添加设备  传递的设备参数devGId 暂时不使用
    @RequestMapping(value = "/bindDev")
    @CrossOrigin
    public String bindDev(String devGId) {

        System.out.println("收到绑定的设备:" + devGId);

        //暂时通知方法更新全局变量数据  后期只增加一个变量  然后剔除这个设备的连接  让设备重连
        InitDataTask.getDevList();

        Device prodDevice = deviceService.selectDeviceByDevGId(devGId);
        if (prodDevice != null) {
            //更新全局变量中的状态
            if (SocketMap.deviceMap.containsKey(devGId)) {
                SocketMap.deviceMap.get(devGId).setIsBind(1);
            }
            for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
                if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                    entry.getValue().getDevice().setIsBind(1);

                    break;
                }
            }
            for (Map.Entry<String, ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()) {
                if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                    entry.getValue().getDevice().setIsBind(1);
                    break;
                }
            }
            for (Map.Entry<String, ConMsg> entry : SocketMap.c2RegPassDeviceMap.entrySet()) {
                if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                    entry.getValue().getDevice().setIsBind(1);
                    break;
                }
            }

        }
        String result = "success";
        //并且添加已注册设备列表

        return result;

    }

    //服务间通讯  修改json设备 采集频率
    @RequestMapping(value = "/editJsonUploadInterval")
    @CrossOrigin
    public ResultStatus editJsonUploadInterval(String devGId, String intervalData) throws InterruptedException {

        ResultStatus msg;
        //判断该设备是否在线

        String command = "sUploadInterval";
        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                conMsg = entry.getValue();
                break;
            }
        }
        if (conMsg != null) {
            //对象锁
            Object object = new Object();

            System.out.println("开始时间：" + DateUtil.getStrDate());
            ConMsg finalConMsg = conMsg;
            new Thread(() -> {
                synchronized (object) {

                    //发送给设备
                    MsgStatus data = new MsgStatus();
                    data.setDevGId(devGId);
                    data.setCommand("sUploadInterval");
                    data.setCommandType("reply");
                    data.setResult("");
                    data.setMsg("");
                    data.setData(intervalData);
                    String ss = JSON.toJSON(data).toString();
                    try {
                        OutBoundHandler.outData(finalConMsg.getCtx(), ss);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    //计数器  //小于30秒
                    int i = 0;
                    while (i < 100) {
                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(command)) {

                            AppData.returnMap.get(devGId).remove(command);
                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();
            synchronized (object) {
                System.out.println("开始等待");
                object.wait(30000L);
            }
            Map<String, Object> resultMap = AppData.returnMap.get(devGId);
            if (resultMap != null && resultMap.size() > 0) {
                String result = resultMap.get(command).toString();
                if (result != null && result.equals("success")) {
                    msg = new ResultStatus("success", "设置成功");
                    //修改数据库
                    //修改本地数据库
                    Device device = deviceService.selectDeviceByDevGId(devGId);
                    devCollectRateService.updateDevCollectRate(device.getDevId(), intervalData);
                    //通知更新全局变量
                    DevManager.updateDevDate(devGId);
                } else {
                    msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
                }

            } else {
                msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
            }

            AppData.returnMap.remove(devGId);

        } else {
            msg = new ResultStatus("error", "设备离线，无法设置");
        }
        return msg;
    }

    //服务间通讯  修改modbus设备 采集频率
    @RequestMapping(value = "/editModbusUploadInterval")
    @CrossOrigin
    public ResultStatus editModbusUploadInterval(String devGId, String intervalData) {


        ResultStatus msg;
        //判断该设备是否在线
        Device device = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                device = entry.getValue().getDevice();
                break;
            }
        }

        if (device != null) {
            //修改数据库
            //修改本地数据库
            Device device1 = deviceService.selectDeviceByDevGId(devGId);
            devCollectRateService.updateDevCollectRate(device1.getDevId(), intervalData);
            //修改全局变量
            DevManager.updateDevDate(devGId);
            msg = new ResultStatus("success", "修改成功");
        } else {
            msg = new ResultStatus("error", "设备离线，无法设置");
        }
        return msg;
    }
    //服务间通讯  修改modbus设备 采集频率
    @RequestMapping(value = "/editC2CustomUploadInterval")
    @CrossOrigin
    public ResultStatus editC2CustomUploadInterval(String devGId, String intervalData) {


        ResultStatus msg;
        //判断该设备是否在线
        Device device = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.c2RegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                device = entry.getValue().getDevice();
                break;
            }
        }

        if (device != null) {
            //修改数据库
            //修改本地数据库
            Device device1 = deviceService.selectDeviceByDevGId(devGId);
            devCollectRateService.updateDevCollectRate(device1.getDevId(), intervalData);
            //修改全局变量
            DevManager.updateDevDate(devGId);
            msg = new ResultStatus("success", "修改成功");
        } else {
            msg = new ResultStatus("error", "设备离线，无法设置");
        }
        return msg;
    }

    //服务间通讯  开启关闭 json 上传数据
    @RequestMapping(value = "/uSetJsonUpLoadSwith")
    @CrossOrigin
    public ResultStatus uSetJsonUpLoadSwith(String devGId, String isOpen) throws InterruptedException {

        ResultStatus msg;
        //判断该设备是否在线

        String command = "sSetUploadData";
        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                conMsg = entry.getValue();
                break;
            }
        }
        if (conMsg != null) {
            //对象锁
            Object object = new Object();

            System.out.println("开始时间：" + DateUtil.getStrDate());
            ConMsg finalConMsg = conMsg;
            String finalIsOpen = isOpen;
            new Thread(() -> {
                synchronized (object) {

                    //发送给设备
                    MsgStatus data = new MsgStatus();
                    data.setDevGId(devGId);
                    data.setCommand("sSetUploadData");
                    data.setCommandType("reply");
                    data.setResult("");
                    data.setMsg("");
                    data.setData(finalIsOpen);
                    String ss = JSON.toJSON(data).toString();
                    try {
                        OutBoundHandler.outData(finalConMsg.getCtx(), ss);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    //计数器  //小于30秒
                    int i = 0;
                    while (i < 100) {
                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(command)) {

                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();
            synchronized (object) {
                System.out.println("开始等待");
                object.wait(30000L);
            }
            Map<String, Object> resultMap = AppData.returnMap.get(devGId);
            if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(command)) {
                if (resultMap.get(command).equals("success")) {

                    AppData.returnMap.get(devGId).remove(command);
                    msg = new ResultStatus("success", "设置成功");
                    //修改数据库
                    //修改本地数据库
                    if (isOpen.equals("on")) {
                        isOpen = "1";
                    } else {
                        isOpen = "0";
                    }
                    Device device = deviceService.selectDeviceByDevGId(devGId);
                    devSwitchService.updateDevSwitch(device.getDevId(), isOpen);
                    //通知更新全局变量
                    DevManager.updateDevDate(devGId);
                } else {
                    msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
                }
            } else {
                msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
            }

            AppData.returnMap.remove(devGId);

        } else {
            msg = new ResultStatus("error", "设备离线，无法设置");
        }
        return msg;
    }


    //服务间通讯  开启关闭 modbus 上传数据
    @RequestMapping(value = "/uSetModbusUpLoadSwith")
    @CrossOrigin
    public ResultStatus uSetModbusUpLoadSwith(String devGId, String isOpen) {


        ResultStatus msg = new ResultStatus("error", "modbus设备暂不支持修改");

        return msg;
    }

    //服务间通讯 获取设备经纬度
    @RequestMapping(value = "/getAddress")
    @CrossOrigin
    public ResultStatus getDevAddress(String devGId) throws InterruptedException {

        ResultStatus msg;
        //判断该设备是否在线

        String command = "getAddress";
        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                conMsg = entry.getValue();
                break;
            }
        }
        if (conMsg != null) {
            //对象锁
            Object object = new Object();

            ConMsg finalConMsg = conMsg;
            new Thread(() -> {
                synchronized (object) {

                    //发送给设备
                    MsgStatus data = new MsgStatus();
                    data.setDevGId(devGId);
                    data.setCommand("getAddress");
                    data.setCommandType("reply");
                    data.setResult("");
                    data.setMsg("");
                    data.setData("");
                    String ss = JSON.toJSON(data).toString();
                    try {
                        OutBoundHandler.outData(finalConMsg.getCtx(), ss);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    //计数器  //小于30秒
                    int i = 0;
                    while (i < 100) {
                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(command)) {
                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();
            synchronized (object) {
                System.out.println("开始等待");
                object.wait(30000L);
            }
            Map<String, Object> resultMap = AppData.returnMap.get(devGId);
            if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(command)) {
                if (resultMap.get(command) != null) {

                    MsgStatus data = (MsgStatus) JSONObject.parse(resultMap.get(command).toString());

                    msg = new ResultStatus("success", "获取成功", data);


                } else {
                    msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
                }
            } else {
                msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
            }

            AppData.returnMap.remove(devGId);

        } else {
            msg = new ResultStatus("error", "设备离线，无法获取");
        }
        return msg;
    }


    //服务间通讯 获取设备实时数据
    @RequestMapping(value = "/getDevCheckData")
    @CrossOrigin
    public ResultStatus getDevCheckData(String devGId) {

        ResultStatus msg;
        Device device = deviceService.selectDeviceByDevGId(devGId);
        if (device != null) {
            //判断设备传输类型
            DevConConfig config = devConConfigService.selectConfigByDevId(device.getDevId());
            if (config != null) {

                //socket设备
                //判断是json 还是modbus  json
                if (config.getDevDataTypeCode().equals(AppData.JSONDataCode)) {

                    //判断设备是否在线
                    Device device1 = null;
                    ConMsg conMsg = null;
                    for (Map.Entry<String, ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()) {
                        if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                            device1 = entry.getValue().getDevice();
                            conMsg = entry.getValue();
                            break;
                        }
                    }

                    if (device1 != null && conMsg != null) {
                        //组合数据发送

                        //发送给设备
                        MsgStatus data = new MsgStatus();
                        data.setDevGId(devGId);
                        data.setCommand("getDevCheckData");
                        data.setCommandType("reply");
                        data.setResult("");
                        data.setMsg("");
                        data.setData("");
                        String ss = JSON.toJSON(data).toString();
                        try {
                            OutBoundHandler.outData(conMsg.getCtx(), ss);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        //发送给测试端
                        WebSocketUtil.sendTestData(device.getDevGId(), ss);

                        msg = new ResultStatus("success", "发送成功");
                    } else {
                        msg = new ResultStatus("error", "设备离线，无法发送");
                    }
                } else {

                    //modbus 设备
                    //组合命令
                    //判断设备是否在线
                    Device device1 = null;
                    ConMsg conMsg = null;
                    for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
                        if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                            device1 = entry.getValue().getDevice();
                            conMsg = entry.getValue();
                            break;
                        }
                    }
                    if (device1 != null && conMsg != null) {
                        //如果指令数量大于1 ，则发数据 建立全局变量 等待全部存储
                        //String 地址位 String 指令
                        Map<String, DevMdtParamConf> commandMap = conMsg.getCommandMap();
                        if (commandMap != null && commandMap.size() > 1) {
                            for (Map.Entry<String, DevMdtParamConf> entry1 : commandMap.entrySet()) {
                                //发送指令
                                byte[] commandByte = ModBusUtil.HexString2Bytes(entry1.getKey());


                                OutBoundHandler.outData(conMsg.getCtx(), commandByte);

                                PrintUtil.print("服务端发送指令-->设备编码：" + device1.getDevGId() + "：" + entry1.getKey());

                                //记录当前发送的指令
                                NowCommandPack nowCommandPack = new NowCommandPack();
                                nowCommandPack.setCommand(entry1.getKey());
                                nowCommandPack.setParamConf(entry1.getValue());
                                nowCommandPack.setSendTime(new Date().getTime());

                                conMsg.setNowCommandPack(nowCommandPack);

                                //发送给测试端
                                WebSocketUtil.sendTestData(device1.getDevGId(), entry1.getKey());


                                boolean flag = true;
                                Long sendTime = new Date().getTime();
                                while (flag) {
                                    //如果配置信息中 当前发送的指令为空  或者超过3秒 就跳出循环
                                    if (conMsg.getNowCommandPack() == null || (new Date().getTime() - sendTime) >= AppConf.commandInterval) {
                                        flag = false;
                                    }
                                }

                            }
                        } else if (commandMap != null && commandMap.size() == 1) {
                            //如果指令数量等于1, 则直接 发送命令 存储数据
                            String command = "";
                            DevMdtParamConf devMdtParamConf = null;
                            for (Map.Entry<String, DevMdtParamConf> entry2 : commandMap.entrySet()) {

                                command = entry2.getKey();
                                devMdtParamConf = entry2.getValue();
                            }


                            //记录当前发送的指令
                            NowCommandPack nowCommandPack = new NowCommandPack();
                            nowCommandPack.setCommand(command);
                            nowCommandPack.setParamConf(devMdtParamConf);
                            nowCommandPack.setSendTime(new Date().getTime());

                            conMsg.setNowCommandPack(nowCommandPack);


                            //去除所有的空格
                            byte[] commandByte = ModBusUtil.HexString2Bytes(command);

                            OutBoundHandler.outData(conMsg.getCtx(), commandByte);
                            PrintUtil.print("服务端发送指令-->设备编码：" + device1.getDevGId() + "：" + command);

                            WebSocketUtil.sendTestData(device.getDevGId(), command);

                        }

                        msg = new ResultStatus("success", "发送成功", commandMap);
                    } else {
                        msg = new ResultStatus("error", "设备离线，发送失败");
                    }
                }


            } else {
                msg = new ResultStatus("error", "该设备配置数据有误，请检查设备配置数据");
            }

        } else {
            msg = new ResultStatus("error", "设备不存在");
        }
        return msg;

    }

    //服务间通讯 获取设备实时数据 新方法  支持等待数据返回 用于一键检测
    @RequestMapping(value = "/getNewDevCheckData")
    @CrossOrigin
    public ResultStatus getNewDevCheckData(String devGId) throws InterruptedException {



        ResultStatus msg;
        Device device = deviceService.selectDeviceByDevGId(devGId);
        if (device != null) {
            //判断设备传输类型
            DevConConfig config = devConConfigService.selectConfigByDevId(device.getDevId());
            if (config != null) {

                //socket设备
                //判断是json 还是modbus  json
                if (config.getDevDataTypeCode().equals(AppData.JSONDataCode)) {

                    //判断设备是否在线
                    Device device1 = null;
                    ConMsg conMsg = null;
                    for (Map.Entry<String, ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()) {
                        if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                            device1 = entry.getValue().getDevice();
                            conMsg = entry.getValue();
                            break;
                        }
                    }

                    if (device1 != null && conMsg != null) {

                        String command = "getDevCheckData";

                        //创建全局变量对象
                        Map<String, Object> resultMap1 = new HashMap<>();
                        resultMap1.put(command, null);
                        AppData.returnMap.put(devGId, resultMap1);


                        //对象锁
                        Object object = new Object();
                        ConMsg finalConMsg = conMsg;
                        new Thread(() -> {
                            synchronized (object) {
                                //发送给设备
                                MsgStatus data = new MsgStatus();


                                data.setDevGId(devGId);
                                data.setCommand(command);
                                data.setCommandType("reply");
                                data.setResult("");
                                data.setMsg("");
                                data.setData("");
                                String ss = JSON.toJSON(data).toString();

                                try {
                                    OutBoundHandler.outData(finalConMsg.getCtx(), ss);

                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }

                                //计数器  //小于10秒
                                int i = 0;
                                while (i < 100) {
                                    Map<String, Object> resultMap = AppData.returnMap.get(devGId);

                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    if (resultMap.containsKey(command) && resultMap.get(command) != null) {
                                        System.out.println("检测："+resultMap.get(command));
                                        object.notify();
                                        break;
                                    }
                                    i++;
                                }
                                object.notify();

                            }
                        }).start();

                        synchronized (object) {
                            System.out.println("开始等待");
                            object.wait(30000L);
                        }

                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);
                        if (resultMap != null && resultMap.containsKey(command) && resultMap.get(command) != null) {
                            List<Param> paramList = (List<Param>) resultMap.get(command);
                            AppData.returnMap.get(devGId).remove(command);
                            msg = new ResultStatus("success", "成功", paramList);
                        } else {
                            msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
                        }

                        AppData.returnMap.remove(devGId);

                    } else {
                        msg = new ResultStatus("error", "设备离线，无法发送");
                    }
                } else {

                    //modbus 设备
                    //组合命令
                    //判断设备是否在线
                    Device device1 = null;
                    ConMsg conMsg = null;
                    for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
                        if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                            device1 = entry.getValue().getDevice();
                            conMsg = entry.getValue();
                            break;
                        }
                    }
                    if (device1 != null && conMsg != null) {
                        //如果指令数量大于1 ，则发数据 建立全局变量 等待全部存储
                        //String 地址位 String 指令
                        Map<String, DevMdtParamConf> commandMap = conMsg.getCommandMap();
                        if (commandMap != null && commandMap.size() > 1) {
                            for (Map.Entry<String, DevMdtParamConf> entry1 : commandMap.entrySet()) {
                                //发送指令
                                byte[] commandByte = ModBusUtil.HexString2Bytes(entry1.getKey());


                                OutBoundHandler.outData(conMsg.getCtx(), commandByte);

                                PrintUtil.print("服务端发送指令-->设备编码：" + device1.getDevGId() + "：" + entry1.getKey());

                                //记录当前发送的指令
                                NowCommandPack nowCommandPack = new NowCommandPack();
                                nowCommandPack.setCommand(entry1.getKey());
                                nowCommandPack.setParamConf(entry1.getValue());
                                nowCommandPack.setSendTime(new Date().getTime());

                                conMsg.setNowCommandPack(nowCommandPack);

                                //发送给测试端
                                //WebSocketUtil.sendTestData(device1.getDevGId(),entry1.getKey());


                                boolean flag = true;
                                Long sendTime = new Date().getTime();
                                while (flag) {
                                    //如果配置信息中 当前发送的指令为空  或者超过3秒 就跳出循环
                                    if (conMsg.getNowCommandPack() == null || (new Date().getTime() - sendTime) >= AppConf.commandInterval) {
                                        flag = false;
                                    }
                                }

                            }
                        } else if (commandMap != null && commandMap.size() == 1) {
                            //如果指令数量等于1, 则直接 发送命令 存储数据
                            String command = "";
                            DevMdtParamConf devMdtParamConf = null;
                            for (Map.Entry<String, DevMdtParamConf> entry2 : commandMap.entrySet()) {

                                command = entry2.getKey();
                                devMdtParamConf = entry2.getValue();
                            }


                            //记录当前发送的指令
                            NowCommandPack nowCommandPack = new NowCommandPack();
                            nowCommandPack.setCommand(command);
                            nowCommandPack.setParamConf(devMdtParamConf);
                            nowCommandPack.setSendTime(new Date().getTime());

                            conMsg.setNowCommandPack(nowCommandPack);


                            //去除所有的空格
                            byte[] commandByte = ModBusUtil.HexString2Bytes(command);

                            OutBoundHandler.outData(conMsg.getCtx(), commandByte);
                            PrintUtil.print("服务端发送指令-->设备编码：" + device1.getDevGId() + "：" + command);

                            //WebSocketUtil.sendTestData(device.getDevGId(),command);

                        }

                        //等待返回数据
                        //对象锁
                        Object object = new Object();
                        ConMsg finalConMsg = conMsg;
                        String command = "getDevCheckData";

                        //创建全局变量对象
                        Map<String, Object> resultMap1 = new HashMap<>();
                        resultMap1.put(command, null);
                        AppData.returnMap.put(devGId, resultMap1);


                        new Thread(() -> {
                            synchronized (object) {
                                //计数器  //小于10秒
                                int i = 0;
                                while (i < 100) {
                                    Map<String, Object> resultMap = AppData.returnMap.get(devGId);
                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    if (resultMap.containsKey(command) && resultMap.get(command) != null) {
                                        object.notify();
                                        break;
                                    }
                                    i++;
                                }
                                object.notify();
                            }
                        }).start();
                        synchronized (object) {
                            System.out.println("开始等待");
                            object.wait(30000L);
                        }

                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);

                        if (resultMap != null && resultMap.containsKey(command) && resultMap.get(command) != null) {
                            List<Param> paramList = (List<Param>) resultMap.get(command);
                            msg = new ResultStatus("success", "成功", paramList);
                            AppData.returnMap.get(devGId).remove(command);
                        } else {
                            msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
                        }

                        AppData.returnMap.remove(devGId);

                    } else {
                        msg = new ResultStatus("error", "设备离线，发送失败");
                    }
                }

            } else {
                msg = new ResultStatus("error", "该设备配置数据有误，请检查设备配置数据");
            }

        } else {
            msg = new ResultStatus("error", "设备不存在");
        }

        return msg;

    }

    //服务间通讯 发送自定义数据
    @RequestMapping(value = "/sendCustomData")
    @CrossOrigin
    public ResultStatus sendCustomData(String devGId, String customData) {

        ResultStatus msg;
        Device device = deviceService.selectDeviceByDevGId(devGId);
        if (device != null) {
            //判断设备传输类型
            DevConConfig config = devConConfigService.selectConfigByDevId(device.getDevId());
            if (config != null) {

                //socket设备
                //判断是json 还是modbus  json
                if (config.getDevDataTypeCode().equals(AppData.JSONDataCode)) {
                    //判断设备是否在线
                    Device device1 = null;
                    ConMsg conMsg = null;
                    for (Map.Entry<String, ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()) {
                        if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                            device1 = entry.getValue().getDevice();
                            conMsg = entry.getValue();
                            break;
                        }
                    }
                    if (device1 != null && conMsg != null) {
                        //发送给设备
                        try {
                            OutBoundHandler.outData(conMsg.getCtx(), customData);

                            PrintUtil.print(devGId + ":发送自定义数据：" + customData);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        //发送给测试端
                        WebSocketUtil.sendTestData(device.getDevGId(), customData);

                        msg = new ResultStatus("success", "发送成功");
                    } else {
                        msg = new ResultStatus("error", "设备离线，无法发送");
                    }
                } else {

                    //modbus 设备
                    //组合命令
                    //判断设备是否在线
                    Device device1 = null;
                    ConMsg conMsg = null;
                    for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
                        if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                            device1 = entry.getValue().getDevice();
                            conMsg = entry.getValue();
                            break;
                        }
                    }
                    if (device1 != null && conMsg != null) {
                        //发送指令
                        byte[] commandByte = ModBusUtil.HexString2Bytes(customData);
                        OutBoundHandler.outData(conMsg.getCtx(), commandByte);
                        PrintUtil.print(devGId + ":发送自定义数据：" + customData);
                        //发送给测试端
                        WebSocketUtil.sendTestData(device.getDevGId(), customData);
                        msg = new ResultStatus("success", "发送成功", customData);

                    } else {
                        msg = new ResultStatus("error", "设备离线，无法发送");
                    }

                }

            } else {
                msg = new ResultStatus("error", "该设备配置数据有误，请检查设备配置数据");
            }

        } else {
            msg = new ResultStatus("error", "设备不存在");
        }
        return msg;
    }


    //更新设备配置 //前期适用于修改数据库后 更新配置
    @RequestMapping(value = "/updateDevConfig")
    @CrossOrigin
    public ResultStatus updateDevConfig(String devGId) {
        ResultStatus msg;
        //修改全局变量
        DevManager.updateDevDate(devGId);
        msg = new ResultStatus("success", "更新成功");
        return msg;
    }

    //更新附加设置设备列表
    @RequestMapping(value = "/updateAddDevData")
    @CrossOrigin
    public ResultStatus updateAddDevData(String devGId) {
        AddSetAutoSend.updateAddSetMsg(devGId);
        ResultStatus msg = new ResultStatus("success", "更新成功");
        return msg;
    }

    //dpd设备读取状态数据
    @RequestMapping(value = "/dpdReadStatus")
    public ResultStatus dpdReadStatus(String devGId) throws InterruptedException {



        String command = "01 03 01 00 00 08 45 F0";

        Device device = deviceService.selectDeviceByDevGId(devGId);
        ResultStatus msg;
        //判断该设备是否在线

        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.c2RegPassDeviceMap.entrySet()) {


            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                conMsg = entry.getValue();
                break;
            }
        }





        if (conMsg != null) {
            //对象锁
            Object object = new Object();

            System.out.println("开始时间：" + DateUtil.getStrDate());
            ConMsg finalConMsg = conMsg;
            new Thread(() -> {
                synchronized (object) {

                    //发送给设备

                    byte[] commandByte = ModBusUtil.HexString2Bytes(command);
                    OutBoundHandler.outData(finalConMsg.getCtx(), commandByte);
                    Map<String, Object> resultMap1 = new HashMap<>();
                    resultMap1.put(command.replace(" ",""),null);
                    AppData.returnMap.put(devGId,resultMap1);
                    System.out.println("自定义设备2"+device.getDevGId()+"发送指令："+command);

                    //计数器  //小于10秒
                    int i = 0;
                    while (i < 100) {
                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(command) && resultMap.get(command) !=null ) {
                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();
            synchronized (object) {
                System.out.println("开始等待");
                object.wait(30000L);
            }
            Map<String, Object> resultMap = AppData.returnMap.get(devGId);


            if (resultMap != null && resultMap.containsKey(command) && resultMap.get(command) !=null  ) {
                System.out.println("指令" + command + "http://返回结果:" + resultMap.get(command));
                msg = new ResultStatus("success", "操作成功", resultMap.get(command));
            } else {
                msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
            }

            AppData.returnMap.remove(devGId);

        } else {
            msg = new ResultStatus("error", "设备离线");
        }
        return msg;
    }
    //dpd设备读取模式
    @RequestMapping(value = "/dpdReadMode")
    public ResultStatus dpdReadMode(String devGId) throws InterruptedException {



        String command = "01 03 02 01 00 05 D5 B1";

        Device device = deviceService.selectDeviceByDevGId(devGId);
        ResultStatus msg;
        //判断该设备是否在线

        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.c2RegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                conMsg = entry.getValue();
                break;
            }
        }

        if (conMsg != null) {
            //对象锁
            Object object = new Object();

            System.out.println("开始时间：" + DateUtil.getStrDate());
            ConMsg finalConMsg = conMsg;
            new Thread(() -> {
                synchronized (object) {

                    //发送给设备

                    byte[] commandByte = ModBusUtil.HexString2Bytes(command);
                    OutBoundHandler.outData(finalConMsg.getCtx(), commandByte);
                    Map<String, Object> resultMap1 = new HashMap<>();
                    resultMap1.put(command.replace(" ",""),null);
                    AppData.returnMap.put(devGId,resultMap1);
                    System.out.println("自定义设备2"+device.getDevGId()+"发送指令:"+command);

                    //计数器  //小于10秒
                    int i = 0;
                    while (i < 100) {
                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(command) && resultMap.get(command) !=null ) {
                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();
            synchronized (object) {
                System.out.println("开始等待");
                object.wait(30000L);
            }
            Map<String, Object> resultMap = AppData.returnMap.get(devGId);


            if (resultMap != null && resultMap.containsKey(command) && resultMap.get(command) !=null ) {
                System.out.println("指令" + command + "http://返回结果:" + resultMap.get(command));

                msg = new ResultStatus("success", "操作成功", resultMap.get(command));
            } else {
                msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
            }

            AppData.returnMap.remove(devGId);

        } else {
            msg = new ResultStatus("error", "设备离线");
        }
        return msg;
    }
    //dpd设备读取模式
    @RequestMapping(value = "/dpdSetData")
    public ResultStatus dpdSetData(String devGId,Integer typeId,String value) throws InterruptedException {

        //typeId  1、流程开启  2、测量模式  3、测量间隔  4、整点设置
        String command = "";
        if(typeId.equals(1)) {
            String hexValue = ModBusUtil.decToHex16(Integer.parseInt(value));
            command = "01 06 02 00 " + hexValue;

            String crc = ModBusUtil.getCRC3(ModBusUtil.HexString2Bytes(command));
            command += crc;
        }
        if(typeId.equals(2)){
            String hexValue = ModBusUtil.decToHex16(Integer.parseInt(value));
            command = "01 06 02 01 " + hexValue;

            String crc = ModBusUtil.getCRC3(ModBusUtil.HexString2Bytes(command));
            command += crc;
        }
        if(typeId.equals(3)){
            String hexValue = ModBusUtil.decToHex32(Integer.parseInt(value));
            String[] data1 = hexValue.split("");

            System.out.println(data1.length);
            String myData1 = data1[4]+data1[5]+data1[6]+data1[7] +data1[0]+data1[1]+data1[2]+data1[3];
            command = "01 10 02 02 00 02 04 " + myData1;

            String crc = ModBusUtil.getCRC3(ModBusUtil.HexString2Bytes(command));
            command += crc;
        }
        if(typeId.equals(4)){
            String hexValue = ModBusUtil.decToHex32(Integer.parseInt(value));
            String[] data1 = hexValue.split("");
            String myData1 = data1[4]+data1[5]+data1[6]+data1[7] +data1[0]+data1[1]+data1[2]+data1[3];
            command = "01 10 02 04 00 02 04 " + myData1;

            String crc = ModBusUtil.getCRC3(ModBusUtil.HexString2Bytes(command));
            command += crc;
        }





        command = command.replaceAll(" ","");

        Device device = deviceService.selectDeviceByDevGId(devGId);
        ResultStatus msg;
        //判断该设备是否在线

        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.c2RegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                conMsg = entry.getValue();
                break;
            }
        }

        if (conMsg != null) {
            //对象锁
            Object object = new Object();

            System.out.println("开始时间：" + DateUtil.getStrDate());
            ConMsg finalConMsg = conMsg;
            String finalCommand = command;
            new Thread(() -> {
                synchronized (object) {

                    //发送给设备
                    byte[] commandByte = ModBusUtil.HexString2Bytes(finalCommand);
                    OutBoundHandler.outData(finalConMsg.getCtx(), commandByte);
                    Map<String, Object> resultMap1 = new HashMap<>();
                    resultMap1.put(finalCommand.replace(" ",""),null);
                    AppData.returnMap.put(devGId,resultMap1);
                    System.out.println("自定义设备2"+device.getDevGId()+"发送指令成功");

                    //计数器  //小于10秒
                    int i = 0;
                    while (i < 100) {
                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(finalCommand) && resultMap.get(finalCommand) !=null ) {
                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();
            synchronized (object) {
                System.out.println("开始等待");
                object.wait(30000L);
            }
            Map<String, Object> resultMap = AppData.returnMap.get(devGId);


            if (resultMap != null && resultMap.containsKey(command) && resultMap.get(finalCommand) !=null) {
                System.out.println("指令" + command + "http://返回结果:" + resultMap.get(command));

                msg = new ResultStatus("success", "操作成功", resultMap.get(command));
            } else {
                msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
            }

            AppData.returnMap.remove(devGId);

        } else {
            msg = new ResultStatus("error", "设备离线");
        }
        return msg;
    }


    //付红航定制柜机 GJ004_V7YK7LDPE 读取阀门
    @RequestMapping("/readStatus")
    public ResultStatus readStatus(String devGId,Integer controlId) throws InterruptedException {

        ResultStatus msg = null;
        Custom2Control custom2Control = custom2ControlService.getById(controlId);

        String command = custom2Control.getCommand();
        Integer devId = custom2Control.getDevId();
        //判断设备是否在线

        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                conMsg = entry.getValue();
                break;
            }
        }
        if(conMsg!=null){
            //对象锁
            Object object = new Object();

            //创建全局变量对象
            Map<String, Object> resultMap1 = new HashMap<>();
            //查询该指令返回的数据回复
            List<Custom2Return> custom2ReturnList = custom2ReturnService.selectListByControlId(controlId);


            resultMap1.put(controlId.toString(), null);

            if (AppData.returnMap.containsKey(devGId)) {
                AppData.returnMap.get(devGId).put(controlId.toString(), null);
            } else {
                AppData.returnMap.put(devGId, resultMap1);
            }
            ConMsg finalConMsg = conMsg;
            new Thread(() -> {
                synchronized (object) {

                    //发送给设备

                    //去除所有的空格
                    byte[] commandByte = ModBusUtil.HexString2Bytes(command);

                    OutBoundHandler.outData(finalConMsg.getCtx(), commandByte);
                    PrintUtil.print("服务端发送指令-->设备编码：" + devGId + "：" + command);
                    //计数器  //小于10秒
                    int i = 0;
                    while (i < 600) {
                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);

                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(controlId.toString()) && resultMap.get(controlId.toString()) != null) {
                            System.out.println("开始激活");
                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();
            synchronized (object) {
                System.out.println("开始等待");
                object.wait(30000L);
            }
            Map<String, Object> resultMap = AppData.returnMap.get(devGId);
            if (resultMap != null && resultMap.containsKey(custom2Control.getControlId().toString())) {
                String result = (String) resultMap.get(custom2Control.getControlId().toString());

                AppData.returnMap.get(devGId).remove(controlId.toString());
                if (EmptyUtil.isNotNull(result)) {
                    PrintUtil.print("指令" + custom2Control.getCommand() + "http://返回结果:" + result);
                    //解析指令
                    //查询所有返回结果数据集合 比对值
                    //进行比对
                    if (custom2ReturnList.size() > 0) {
                        for (Custom2Return custom2Return : custom2ReturnList) {
                            String returnData = custom2Return.getControlReturnData().replaceAll(" ", "");
                            String resultData = result.replaceAll(" ", "");
                            if (returnData.equals(resultData)) {
                                msg = new ResultStatus("success", custom2Return.getStatus());
                            }
                        }
                    } else {
                        msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息1");
                    }

                } else {
                    msg = new ResultStatus("error", "设备无响应");
                }

            } else {
                msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息2");
            }


        }else {
            msg = new ResultStatus("error", "设备不在线");
        }
        //AppData.returnMap.get(devGId).remove(controlId.toString());
        return msg;
    }
    //付红航定制柜机 GJ004_V7YK7LDPE 写入阀门
    @RequestMapping("/makeValve")
    public ResultStatus makeValve(String devGId,Integer controlId) throws InterruptedException {

        ResultStatus msg = null;

        Custom2Control custom2Control = custom2ControlService.getById(controlId);

        String command = custom2Control.getCommand();
        //判断设备是否在线

        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
            System.out.println(entry.getValue().getDevice().getDevGId());
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                conMsg = entry.getValue();
                break;
            }
        }
        if(conMsg!=null){
            //对象锁
            Object object = new Object();

            //创建全局变量对象
            Map<String, Object> resultMap1 = new HashMap<>();
            //查询该指令返回的数据回复
            List<Custom2Return> custom2ReturnList = custom2ReturnService.selectListByControlId(controlId);


            resultMap1.put(controlId.toString(), null);

            if (AppData.returnMap.containsKey(devGId)) {
                AppData.returnMap.get(devGId).put(controlId.toString(), null);
            } else {
                AppData.returnMap.put(devGId, resultMap1);
            }
            ConMsg finalConMsg = conMsg;


            new Thread(() -> {
                synchronized (object) {

                    //发送给设备

                    //去除所有的空格
                    byte[] commandByte = ModBusUtil.HexString2Bytes(command);

                    OutBoundHandler.outData(finalConMsg.getCtx(), commandByte);
                    PrintUtil.print("服务端发送指令-->设备编码：" + devGId + "：" + command);
                    //计数器  //小于10秒
                    int i = 0;
                    while (i < 600) {
                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);

                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(controlId.toString()) && resultMap.get(controlId.toString()) != null) {
                            System.out.println("开始激活");
                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();
            synchronized (object) {
                System.out.println("开始等待");
                object.wait(30000L);
            }
            Map<String, Object> resultMap = AppData.returnMap.get(devGId);


            if (resultMap != null && resultMap.containsKey(custom2Control.getControlId().toString())) {


                String result = (String) resultMap.get(custom2Control.getControlId().toString());

                AppData.returnMap.get(devGId).remove(controlId.toString());
                if (EmptyUtil.isNotNull(result)) {
                    PrintUtil.print("指令" + custom2Control.getCommand() + "http://返回结果:" + result);
                    //解析指令
                    //查询所有返回结果数据集合 比对值
                    //进行比对
                    if (custom2ReturnList.size() > 0) {
                        for (Custom2Return custom2Return : custom2ReturnList) {
                            String returnData = custom2Return.getControlReturnData().replaceAll(" ", "");
                            String resultData = result.replaceAll(" ", "");
                            if (returnData.equals(resultData)) {
                                msg = new ResultStatus("success", custom2Return.getStatus());
                                //清除全局变量
                            }
                        }
                    } else {
                        msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息1");
                    }

                } else {
                    msg = new ResultStatus("error", "设备无响应");
                }

            } else {
                msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息2");
            }
        }else {
            msg = new ResultStatus("error", "设备不在线");
        }
        AppData.returnMap.get(devGId).remove(controlId.toString());
        return msg;
    }

    /*//服务间通讯 删除设备 未写完
    @RequestMapping(value = "/mDeleteDevice")
    @CrossOrigin
    public ResultStatus mDeleteDevice(Integer devId,String checkCode){

        ResultStatus msg;
        //判断该设备是否在线

        ConMsg conMsg = null;
        for(Map.Entry<String,ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()){
            if(entry.getValue().getDevice().getDevGId().equals(devGId)){
                conMsg = entry.getValue();
                break;
            }
        }
        if(conMsg!=null){
            //对象锁
            Object object = new Object();

            System.out.println("开始时间："+ DateUtil.getStrDate());
            ConMsg finalConMsg = conMsg;
            String finalIsOpen = isOpen;
            new Thread(() -> {
                synchronized(object) {

                    //发送给设备
                    MsgStatus data = new MsgStatus();
                    data.setDevGId(devGId);
                    data.setCommand("sSetUploadData");
                    data.setCommandType("reply");
                    data.setResult("");
                    data.setMsg("");
                    data.setData(finalIsOpen);
                    String ss = JSON.toJSON(data).toString();
                    try {
                        OutBoundHandler.outData(finalConMsg.getCtx(),ss);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    //计数器  //小于30秒
                    int i = 0;
                    while (i<100){
                        String result  = AppData.returnMap.get(devGId);
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if(result!=null){
                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();
            synchronized(object) {
                System.out.println("开始等待");
                object.wait(30000L);
            }
            String result  = AppData.returnMap.get(devGId);
            if(result!=null && result.equals("success")){
                msg = new ResultStatus("success","设置成功");
                //修改数据库
                //修改本地数据库
                if(isOpen.equals("on")){
                    isOpen = "1";
                }else {
                    isOpen = "0";
                }
                Device device = deviceService.selectDeviceByDevGId(devGId);
                devSwitchService.updateDevSwitch(device.getDevId(),isOpen);
                //通知更新全局变量
                DevManager.updateDevDate(devGId);

            }else{
                msg = new ResultStatus("error","设备响应超时，请稍后查看日志信息");
            }

            AppData.returnMap.remove(devGId);

        }else{
            msg = new ResultStatus("error","设备离线，无法设置");
        }
        return msg;

    }*/


    //微型水站 返控设置 读取配置信息 和设置数据 tcp服务
    @RequestMapping(value = "/selectAndSetShuizhanConf")
    @CrossOrigin
    public ResultStatus selectAndSetShuizhanConf(@RequestBody String command) throws InterruptedException {

        MsgStatus data = gson.fromJson(command, MsgStatus.class);

        String devGId = data.getDevGId();

        String command1 = data.getCommand();

        ResultStatus msg;
        //判断该设备是否在线

        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()) {
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                conMsg = entry.getValue();
                break;
            }
        }

        if (conMsg != null) {
            //对象锁
            Object object = new Object();

            System.out.println("开始时间：" + DateUtil.getStrDate());
            ConMsg finalConMsg = conMsg;
            new Thread(() -> {
                synchronized (object) {

                    //发送给设备
                    try {
                        OutBoundHandler.outData(finalConMsg.getCtx(), command);
                        System.out.println("水站发送指令成功");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    //计数器  //小于10秒
                    int i = 0;
                    while (i < 100) {
                        Map<String, Object> resultMap = AppData.returnMap.get(devGId);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(command1)) {
                            object.notify();
                            break;
                        }
                        i++;
                    }
                    object.notify();
                }

            }).start();
            synchronized (object) {
                System.out.println("开始等待");
                object.wait(30000L);
            }
            Map<String, Object> resultMap = AppData.returnMap.get(devGId);


            if (resultMap != null && resultMap.containsKey(command1)) {
                System.out.println("指令" + command1 + "http://返回结果:" + resultMap.get(command1));
                MsgStatus dataMsg = JSON.parseObject(resultMap.get(command1).toString(), MsgStatus.class);
                msg = new ResultStatus("success", "操作成功", dataMsg);
            } else {
                msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息");
            }

            AppData.returnMap.remove(devGId);

        } else {
            msg = new ResultStatus("error", "设备离线，无法设置");
        }
        return msg;
    }





    /*//服务间通讯 修改设备心跳包
    @RequestMapping(value = "/mSetDevHeartData")
    @CrossOrigin
    public ResultStatus mSetDevHeartData(String devGId,String heartData){
        ResultStatus msg;
        //判断该设备是否在线

        ConMsg conMsg = null;
        for(Map.Entry<String,ConMsg> entry : SocketMap.jRegPassDeviceMap.entrySet()){
            if(entry.getValue().getDevice().getDevGId().equals(devGId)){
                conMsg = entry.getValue();
                break;
            }
        }
        for(Map.Entry<String,ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()){
            if(entry.getValue().getDevice().getDevGId().equals(devGId)){
                conMsg = entry.getValue();
                break;
            }
        }
        if(conMsg!=null){

                //修改数据库
                //修改本地数据库
                Device device = deviceService.selectDeviceByDevGId(devGId);
                String isOpenCode = sysDictItemService.selectDictItemByDictName("心跳包").get(0).getDictCode();
                String dataTypeCode = sysDictItemService.selectDictItemByDictName("设备设置").get(0).getDictCode();
                devDataService.editDevDataValue(device.getDevId(),dataTypeCode,isOpenCode,heartData);
                //通知更新全局变量
                DevManager.updateDevDate(devGId);
            msg = new ResultStatus("success","设置成功");
        }else{
            //修改数据库
            //修改本地数据库
            Device device = deviceService.selectDeviceByDevGId(devGId);
            String isOpenCode = sysDictItemService.selectDictItemByDictName("心跳包").get(0).getDictCode();
            String dataTypeCode = sysDictItemService.selectDictItemByDictName("设备设置").get(0).getDictCode();
            devDataService.editDevDataValue(device.getDevId(),dataTypeCode,isOpenCode,heartData);
            msg = new ResultStatus("success","设置成功");
        }
        return msg;
    }
*/


    public String getRemoteAddress(ChannelHandlerContext ctx) {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        Integer port = ipSocket.getPort();
        String ip = clientIp + ":" + port;
        return ip;
    }


}
